//
//  ChooseGoodsPropertyViewController.m
//  购物车弹窗
//
//  Created by 宓珂璟 on 16/6/23.
//  Copyright © 2016年 宓珂璟. All rights reserved.
//

#import "ChooseGoodsPropertyViewController.h"
#import "ProductTableViewCell.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "UIViewController+KNSemiModal.h"
#import <UIImageView+WebCache.h>
#import "Header.h"
@interface ChooseGoodsPropertyViewController () <UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (weak, nonatomic) IBOutlet UILabel *chooseLabel;
@property (weak, nonatomic) IBOutlet UIButton *confirmButton;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataSource;

@property (nonatomic,assign) NSInteger idx1;
@property (nonatomic,assign) NSInteger idx2;
@property (nonatomic,assign) NSInteger idx3;
@property (nonatomic,assign) NSInteger idx4;
@property (nonatomic,assign) NSInteger idx5;

@property (weak, nonatomic) IBOutlet UIButton *confirmButtom;

@property (nonatomic, strong) UILabel *lb;
@property (nonatomic, strong) UIButton *bt_add;
@property (nonatomic, strong) UITextField *tf_count;
@property (nonatomic, strong) UIButton *bt_reduce;
@end


static NSString *identyfy1 = @"ProductTableViewCell";
//static NSString *identyfy2 = @"CountTableViewCell";

@implementation ChooseGoodsPropertyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
//    if (self.enterType == FirstEnterType) {
//        [self.confirmButtom setTitle:@"确定" forState:UIControlStateNormal];
//    }
//    else
//    {
//        [self.confirmButtom setTitle:@"确定" forState:UIControlStateNormal];
//    }
    _dataSource = [[NSMutableArray alloc] initWithArray:@[
                                                          @{@"颜色":@[@"红色",@"蓝色",@"藏青色"]},
                                                          @{@"类别":@[@"立柱",@"四腿",@"两个腿"]},
                                                          @{@"搭配":@[@"单桌",@"一桌四椅",@"一桌两仪",@"一桌三一"]}
                                                          ]];
    self.imageView.layer.cornerRadius = 5.0f;
    self.imageView.clipsToBounds = YES;
    [self.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://p3.wmpic.me/article/2016/07/08/1467959558_eOMTgkCd.jpg"] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        if (image && cacheType == SDImageCacheTypeNone) {
            self.imageView.alpha = 0;
            [UIView animateWithDuration:1.0 animations:^{
               
                self.imageView.alpha = 1.0f;
            }];
        }
        else
        {
            self.imageView.alpha = 1.0f;
        }
        
        
    }];
    [self.tableView registerNib:[UINib nibWithNibName:identyfy1 bundle:nil] forCellReuseIdentifier:identyfy1];
//    [self.tableView registerNib:[UINib nibWithNibName:identyfy2 bundle:nil] forCellReuseIdentifier:identyfy2];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.001;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerview = [[UIView alloc] init];
    headerview.backgroundColor = [UIColor colorWithWhite:0.900 alpha:1.000];
    return headerview;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 50;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor whiteColor];
    self.lb = [[UILabel alloc] initWithFrame:CGRectMake(10, 10 , 100, 30)];
    self.lb.text = @"购买数量";
    self.lb.textColor = [UIColor redColor];
    self.lb.font = [UIFont systemFontOfSize:14];
    [view addSubview:self.lb];
    
    self.bt_add= [UIButton buttonWithType:UIButtonTypeCustom];
    self.bt_add.frame = CGRectMake(self.view.frame.size.width-10-40, 10,40, 30);
    [self.bt_add setBackgroundColor:[UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1]];
    [self.bt_add addTarget:self action:@selector(add) forControlEvents:UIControlEventTouchUpInside];
    [self.bt_add setTitleColor:[UIColor blackColor] forState:0];
    self.bt_add.titleLabel.font = [UIFont systemFontOfSize:20];
    [self.bt_add setTitle:@"+" forState:0];
    [view addSubview:self.bt_add];
    
    self.tf_count = [[UITextField alloc] initWithFrame:CGRectMake(self.bt_add.frame.origin.x -45, 10, 40, 30)];
    self.tf_count.text = @"1";
    self.tf_count.textAlignment = NSTextAlignmentCenter;
    self.tf_count.font = [UIFont systemFontOfSize:15];
    self.tf_count.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1];
    [self.tf_count addTarget:self action:@selector(putoutCount) forControlEvents:(UIControlEventEditingDidBegin)];
    [view addSubview:self.tf_count];
    
    self.bt_reduce= [UIButton buttonWithType:UIButtonTypeCustom];
    self.bt_reduce.frame = CGRectMake(self.tf_count.frame.origin.x -45, 10, 40, 30);
    [self.bt_reduce setBackgroundColor:[UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1]];
    [self.bt_reduce setTitleColor:[UIColor blackColor] forState:0];
    self.bt_reduce.titleLabel.font = [UIFont systemFontOfSize:20];
    [self.bt_reduce setTitle:@"-" forState:0];
    [self.bt_reduce addTarget:self action:@selector(reduce) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:self.bt_reduce];
    
    
    return view;
}
// 购买数量增加
-(void)add
{
    int count =[self.tf_count.text intValue];
    self.tf_count.text = [NSString stringWithFormat:@"%d",count+1];
    NSLog(@"%@",self.tf_count.text);
}
//购买数量减少
-(void)reduce
{
    int count =[self.tf_count.text intValue];
    self.tf_count.text = [NSString stringWithFormat:@"%d",count-1];
    NSLog(@"%@",self.tf_count.text);
}
-(void)putoutCount{
    NSLog(@"%@",self.tf_count.text);
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self dismissViewControllerAnimated:YES completion:nil];
//    UIViewController * parent = [self.view containingViewController];
//    if ([parent respondsToSelector:@selector(dismissSemiModalView)]) {
//        [parent dismissSemiModalView];
//    }
}

- (IBAction)confirm:(id)sender
{

    [AppTools createAFN:[NSString stringWithFormat:@"http://api03.m0571.com/WebJson.aspx?book=InsertPaycat&giftid=%ld&giftdetailid=%ld&count=%@&type1=%@&userid=%@",self.orderId,self.shopId,self.tf_count.text,@"white,m",USERID] success:^(id result) {
//        NSLog(@"%@",result);
        
        
    } error:^(NSError *error) {
        
        
    }];
    [self dismissViewControllerAnimated:YES completion:^{
//        [AppTools HUDAlert:self string:@"添加成功"];
        
    }];
//    UIViewController * parent = [self.view containingViewController];
//    if ([parent respondsToSelector:@selector(dismissSemiModalView)]) {
//        [parent dismissSemiModalView];
//    }
//    if (self.enterType == FirstEnterType)
//    {
//        self.block();
//    }
    
    

}


#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *ID = nil;
//    if (indexPath.row == self.dataSource.count) {
//        ID = identyfy2;
//    }
//    else
//    {
        ID = identyfy1;
//    }
    ProductTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [self congifCell:cell indexpath:indexPath];
    return cell;
}

- (void)congifCell:(ProductTableViewCell *)cell indexpath:(NSIndexPath *)indexpath
{
    if (indexpath.row < self.dataSource.count) {
        UIColor *selectedColor = [UIColor colorWithRed:255/255.0 green:174/255.0 blue:1/255.0 alpha:1];
        
        cell.leftTitleLabel.text = [self.dataSource[indexpath.row] allKeys][0];
        [cell.tagView removeAllTags];
        // 这东西非常关键
        cell.tagView.preferredMaxLayoutWidth = [UIScreen mainScreen].bounds.size.width - 70;
        cell.tagView.padding = UIEdgeInsetsMake(5, 10, 5, 10);
        cell.tagView.lineSpacing = 20;
        cell.tagView.interitemSpacing = 11;
        NSArray *arr = [self.dataSource[indexpath.row] allValues][0];
        [arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            SKTag *tag = [[SKTag alloc] initWithText:arr[idx]];
            tag.font = [UIFont boldSystemFontOfSize:13];
//
//            tag.bgImg = [UIImage imageNamed:@"FE9C970DA8AD4263ABA40AFA572A0538.jpg"];
            tag.padding = UIEdgeInsetsMake(5, 5, 5, 5);
            tag.cornerRadius = 5;
            tag.borderWidth = 1;
            tag.borderColor = [UIColor lightGrayColor];
            if (indexpath.row == 0) {
                if (idx == self.idx1) {
                    tag.textColor = [UIColor whiteColor];
                    tag.bgColor = [UIColor redColor];
//                    tag.bgColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];
                }
            }
            if (indexpath.row == 1) {
                if (idx == self.idx2) {
                    tag.textColor = [UIColor whiteColor];
                    tag.bgColor = [UIColor redColor];
                    //                    tag.bgColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];
                }
            }
            if (indexpath.row == 2) {
                if (idx == self.idx3) {
                    tag.textColor = [UIColor whiteColor];
                    tag.bgColor = [UIColor redColor];
                    //                    tag.bgColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];
                }
            }
            if (indexpath.row == 3) {
                if (idx == self.idx4) {
                    tag.textColor = [UIColor whiteColor];
                    tag.bgColor = [UIColor redColor];
                    //                    tag.bgColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];
                }
            }
            if (indexpath.row == 4) {
                if (idx == self.idx5) {
                    tag.textColor = [UIColor whiteColor];
                    tag.bgColor = [UIColor redColor];
                    //                    tag.bgColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];
                }
            }
//            else
//            {
//                if (idx == self.idx2) {
//                    tag.textColor = selectedColor;
//                    tag.bgColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];
//                }
//            }
            [cell.tagView addTag:tag];
            
            
        }];
        
        cell.tagView.didTapTagAtIndex = ^(NSUInteger idx,SKTagView *tagView)
        {
            
            ProductTableViewCell *cell = (ProductTableViewCell *)[[tagView superview] superview];
            NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
            if (indexPath.row == 0) {
                self.idx1 = idx;
            }
            if (indexPath.row == 1) {
                self.idx2 = idx;
            }
            if (indexPath.row == 2) {
                self.idx3 = idx;
            }
            if (indexPath.row == 3) {
                self.idx4 = idx;
            }
            if (indexPath.row == 4) {
                self.idx5 = idx;
            }
//            else
//            {
//                self.idx2 = idx;
//            }
            NSLog(@"点击了第%ld行，第%ld个",indexPath.row,idx);
//            NSString *name = [self.dataSource[indexPath.row] allValues][0][idx];
            
//            self.chooseLabel.text = [NSString stringWithFormat:@"%@:%@,%@:%@",[self.dataSource[0] allKeys][0],[self.dataSource[0] allValues][0][self.idx1],[self.dataSource[1] allKeys][0],[self.dataSource[1] allValues][0][self.idx2]];
            [self.tableView reloadData];
//            TWTProductModelDetail *modelDetail = self.modelDetailDataSource[indexPath.row - 1];
//            for (NSInteger i = 0; i < modelDetail.values.count; i ++)
//            {
//                if (i == idx)
//                {
//                    modelDetail.selectValue = modelDetail.values[i];
//                }
//            }
//            [self.tableView reloadRowsAtIndexPaths:@[indexpath] withRowAnimation:UITableViewRowAnimationNone];
        };
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row == self.dataSource.count) {
        return 50;
    }
    else
    {
        return 150;
//        NSLog(@"--%@",self.dataSource[indexPath.row]);
//        NSArray *array = self.dataSource[indexPath.row];
//        return [self.dataSource[indexPath.row] allValues].count *80;
//        return [tableView fd_heightForCellWithIdentifier:identyfy1 cacheByIndexPath:indexPath configuration:^(id cell) {
//           
//            [self congifCell:cell indexpath:indexPath];
//        }];
    }
}

- (void)dealloc
{
    NSLog(@"%s____dealloc",object_getClassName(self));
}




- (NSMutableArray *)dataSource
{
    if (_dataSource == nil) {
        _dataSource = [[NSMutableArray alloc] initWithArray:@[
      @{@"颜色":@[@"红色",@"蓝色",@"藏青色"]},
      @{@"类别":@[@"立柱",@"四腿",@"两个腿"]},
      @{@"搭配":@[@"单桌",@"一桌四椅",@"一桌两仪",@"一桌三一"]}
      ]];
    }
    return _dataSource;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
